from app.graph_rag.financial_kg import FinancialKnowledgeGraph
from app.graph_rag.query_engine import GraphRAGQuery
import json
import os
from app.core.logger import get_logger

logger = get_logger('graph_rag.service')

class GraphRAGService:
    """GraphRAG服务"""
    
    _instance = None
    _initialized = False
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(GraphRAGService, cls).__new__(cls)
        return cls._instance
    
    def __init__(self):
        if not self._initialized:
            self.knowledge_graph = None
            self.query_engine = None
            self._initialized = True
    
    def initialize(self):
        """初始化GraphRAG服务"""
        try:
            if self.knowledge_graph is None:
                logger.info("正在初始化金融知识图谱...")
                # 获取数据库路径
                db_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 
                                      "dataset", "sqlite", "博金杯比赛数据.db")
                logger.info(f"使用数据库路径: {db_path}")
                
                self.knowledge_graph = FinancialKnowledgeGraph(db_path)
                self.knowledge_graph.build_knowledge_graph()
                logger.info("金融知识图谱初始化完成")
            
            if self.query_engine is None:
                logger.info("正在初始化GraphRAG查询引擎...")
                self.query_engine = GraphRAGQuery(self.knowledge_graph)
                logger.info("GraphRAG查询引擎初始化完成")
                
        except Exception as e:
            logger.error(f"初始化GraphRAG服务时出错: {e}")
            raise
    
    def query(self, query_text: str) -> str:
        """
        查询GraphRAG
        
        Args:
            query_text: 查询文本
            
        Returns:
            查询结果
        """
        if self.query_engine is None:
            self.initialize()
        
        return self.query_engine.query_financial_relationships(query_text)
    
    def analyze_investment_pattern(self, fund_code: str) -> str:
        """
        分析基金投资模式
        
        Args:
            fund_code: 基金代码
            
        Returns:
            分析结果
        """
        if self.query_engine is None:
            self.initialize()
        
        return self.query_engine.find_investment_patterns(fund_code)
    
    def get_entity_relationships(self, entity_id: str) -> dict:
        """
        获取实体关系信息
        
        Args:
            entity_id: 实体ID
            
        Returns:
            关系信息
        """
        if self.knowledge_graph is None:
            self.initialize()
        
        return self.knowledge_graph.query_entity_relationships(entity_id)
    
    def find_paths(self, source_id: str, target_id: str) -> list:
        """
        查找实体间路径
        
        Args:
            source_id: 源实体ID
            target_id: 目标实体ID
            
        Returns:
            路径列表
        """
        if self.knowledge_graph is None:
            self.initialize()
        
        return self.knowledge_graph.find_paths_between_entities(source_id, target_id)

# 全局实例
graph_rag_service = GraphRAGService()

# MCP兼容的函数接口
def mcp_graph_rag_query(query_text: str) -> str:
    """
    MCP兼容的GraphRAG查询接口
    
    Args:
        query_text: 查询文本
        
    Returns:
        查询结果
    """
    return graph_rag_service.query(query_text)

def mcp_analyze_investment_pattern(fund_code: str) -> str:
    """
    MCP兼容的基金投资模式分析接口
    
    Args:
        fund_code: 基金代码
        
    Returns:
        分析结果
    """
    return graph_rag_service.analyze_investment_pattern(fund_code)

def mcp_get_entity_relationships(entity_id: str) -> dict:
    """
    MCP兼容的实体关系获取接口
    
    Args:
        entity_id: 实体ID
        
    Returns:
        关系信息
    """
    return graph_rag_service.get_entity_relationships(entity_id)

def mcp_find_entity_paths(source_id: str, target_id: str) -> list:
    """
    MCP兼容的实体路径查找接口
    
    Args:
        source_id: 源实体ID
        target_id: 目标实体ID
        
    Returns:
        路径列表
    """
    return graph_rag_service.find_paths(source_id, target_id)